using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Collections;
using System.Web.Script.Serialization;
using System.Collections.Generic;
/// <summary>
/// Summary description for CategoryView
/// </summary>
public class CategoryView
{
    DynamicDisplayI DDI;
    HDDatabase HDD;
    GridPaging gp;
    public CategoryView()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public bool GenerateCategory(DataTable dtaPage, DataTable dtaPageSrch, DataTable dtaPageKeys, DataTable dtaPageControls, string groupingField, HtmlForm frmObj, bool bRead, bool bCreate, bool bEdit, bool bDelete, string strPagesetRowId, DataSet dsePageObj)//Added BY DHanapal ON Jan 24 2011
    {
        gp = new GridPaging();
        GenerateGrid objGG = new GenerateGrid();
        DDI = new DynamicDisplayI();
        string strTableNames = objGG.GetTableNames(dtaPage, dtaPageSrch);
        bool bIsCombinedOrderBy = false;
        string sCombinedOrderBy = "";
        string Order = " desc";
        string sFieldAlias = "";
        string sQuickSearch = "";
        //string sOrderby = gp.getSortField(dtaPageControls, ref Order);
        string sOrderby = "modified_at";
        Hashtable hsDatatype = new Hashtable();
        string CategoryTotalRecordCount = "0";
        string strSql = getDistinctCategoryQuery(dtaPage, dtaPageKeys, dtaPageSrch, dtaPageControls, ref hsDatatype, "", ref sFieldAlias, frmObj, sQuickSearch, ref bIsCombinedOrderBy, sOrderby, ref  sCombinedOrderBy, groupingField, ref CategoryTotalRecordCount,false);

        bool blnActions = false; // Below lines are added by 'Imran Gani' on 04-June-2012, for action status.
        if (dsePageObj.Tables.Contains("Page Actions") && dsePageObj.Tables["Page Actions"] != null)
            if (dsePageObj.Tables["Page Actions"].Rows.Count > 0)
                blnActions = true;

        #region Old Lines commented by 'Imran Gani' on 14-Mar-2014, to avoid top key from query and use ROW_NUMBER().
        //if (Order.Trim() == "asc")
        //{
        //    strSql = strSql.TrimEnd() + " order by " + sOrderby + " " + " desc" + " ,[keys] desc ";
        //}
        //else
        //{
        //    strSql = strSql.TrimEnd() + " order by " + sOrderby + " " + " asc" + " ,[keys] desc ";
        //}
        //sFieldAlias += "," + "keys";

        //strSql = "Select top " + GlobalValues.intNoOfRecordsPerPage.ToString() + " " + sFieldAlias + " from ( " + strSql + ") as tt order by " + sOrderby + " " + Order + " ,[keys] asc ";

        ////strSql = "Select top " + GlobalValues.intNoOfRecordsPerPage.ToString() + " " + sFieldAlias + " from ( " + strSql + ") as tt order by " + groupingField + " asc";
        #endregion

        strSql = "Select " + sFieldAlias + ", keys from ( " + strSql + ") as tt where [row] between 1 and " + GlobalValues.intNoOfRecordsPerPage + " order by [row] asc";

        System.Web.UI.WebControls.HiddenField hfcategoryCount = (System.Web.UI.WebControls.HiddenField)DDI.FindControl(frmObj.Controls, "hdnCategoryPaging");
        if (hfcategoryCount != null)
            hfcategoryCount.Value = CategoryTotalRecordCount.ToString() + "|" + CategoryTotalRecordCount.ToString() + "|" + GlobalValues.intNoOfRecordsPerPage.ToString() + "|" + "1"; //TotalRecordCount | CurrentRecordCount | Limit | pageCount

        System.Web.UI.WebControls.HiddenField hfPagePermission = (System.Web.UI.WebControls.HiddenField)DDI.FindControl(frmObj.Controls, "hdnPagePermission");
        if (hfPagePermission != null)
            hfPagePermission.Value = bRead.ToString() + "|" + bCreate.ToString() + "|" + bEdit.ToString() + "|" + bDelete.ToString() + "|" + blnActions.ToString(); // Modified by 'Imran Gani' on 04-June-2012, for action status.

        System.Web.UI.WebControls.HiddenField hfgroupingField = (System.Web.UI.WebControls.HiddenField)DDI.FindControl(frmObj.Controls, "hdngroupingField");
        if (hfgroupingField != null)
            hfgroupingField.Value = groupingField.ToString();

        System.Web.UI.HtmlControls.HtmlGenericControl categoryDiv = (System.Web.UI.HtmlControls.HtmlGenericControl)DDI.FindControl(frmObj.Controls, "panelDynamicCategory");

        if (strSql != "")
        {
            try
            {
                HDD = new HDDatabase();
                DataSet dseObj = HDD.GetDataset(strSql);
                if (dseObj.Tables[0].Rows.Count > 0)
                {
                    checkandUpdateDataBindValues(ref dseObj, dtaPage, dtaPageControls, groupingField);

                    if (categoryDiv != null)
                    {
                        
                        BuildCategoryHeader(dseObj, dtaPage, dtaPageSrch, dtaPageKeys, dtaPageControls, frmObj, bRead, bCreate, bEdit, bDelete, groupingField, sOrderby, Order, strPagesetRowId, dsePageObj, hfcategoryCount.Value); //Modified By Dhanapal On Feb 01 2011
                    }
                }
                else
                {
                    LiteralControl lcmsg = new LiteralControl();
                    lcmsg.Text = "<font class='controlFont'>No records available.</font>";
                    categoryDiv.Controls.Add(lcmsg);
                    categoryDiv.Attributes.Add("class", "dynamicTreeholder");
                    return true;

                }
            }
            catch (Exception e1)
            {
                LogWriter.WriteLog("Error in Generate Category.");
                return false;
            }

        }
        return true;
    }

    private void checkandUpdateDataBindValues(ref DataSet dseObj, DataTable dtaPage ,DataTable dtaPageControls ,string groupingField)
    {
        gp = new GridPaging();
        for (int i = 0; i < dtaPage.Rows.Count; i++)
        {
            string strPageId, strSearchAttribName, strBindRowID;
            strPageId = dtaPage.Rows[i]["af_row_id"].ToString();

            DataRow[] droPageCtrl = dtaPageControls.Select("page_id='" + strPageId.Replace("'", "''") + "' and  control_attrib_id = '" + groupingField + "'", "");
            for (int j = 0; j < droPageCtrl.Length; j++)
            {
                //strSearchAttribName = droPageSrch[j]["search_attrib_name"].ToString();
                strSearchAttribName = droPageCtrl[j]["control_attrib_id"].ToString();
                if (strSearchAttribName == "")
                {
                    strSearchAttribName = droPageCtrl[j]["control_attrib_id"].ToString();
                }
                strBindRowID = droPageCtrl[j]["control_bind_id"].ToString();
                if (strBindRowID != "")
                {
                    //string search_attrib_name = droPageSrch[j]["search_attrib_name"].ToString();
                    string search_attrib_name = droPageCtrl[j]["control_attrib_id"].ToString();
                    string sBindStoreField = "", sBindDisplayField = "", sBindTable = "";
                    DataRow drBind = null;
                    if (strBindRowID != "") drBind = HDD.GetTableRow("select * from sy_bnd where af_row_id = '" + strBindRowID + "';");
                    if (drBind != null)
                    {
                        sBindStoreField = drBind["bind_value"].ToString();
                        sBindDisplayField = drBind["bind_text"].ToString();
                        sBindTable = drBind["bind_table"].ToString();
                        gp.addBindColumn(dseObj, search_attrib_name);

                        string af_row_ids = "";
                        if (dseObj != null)
                        {
                            if (dseObj.Tables.Count > 0)
                            {
                                if (dseObj.Tables[0].Rows.Count > 0)
                                {
                                    af_row_ids = gp.getDistinct(dseObj.Tables[0], search_attrib_name);
                                }
                            }
                        }
                        string sSql = "";
                        DataTable dt = new DataTable();
                        if (af_row_ids != "")
                        {
                            sSql = "select " + sBindDisplayField + "," + sBindStoreField + " from " + sBindTable + " where " + sBindStoreField + " in (" + af_row_ids + ")";
                        }
                        else
                        {
                            sSql = "select " + sBindDisplayField + "," + sBindStoreField + " from " + sBindTable;
                        }
                        dt = HDD.GetDataTable(sSql, sBindTable);
                        dseObj.Tables[0].Columns.Add(strSearchAttribName + "Bind_Storage_Value", typeof(string)); //To Maintain The Bind Id Value
                        foreach (DataRow dr in dseObj.Tables[0].Rows)
                        {
                            if (dr[strSearchAttribName].ToString() == "") dr[strSearchAttribName] = "";
                            else
                            {
                                DataRow[] drr = dt.Select("" + sBindStoreField + "= '" + dr[strSearchAttribName].ToString().Replace("'", "''") + "'");
                                if (drr.Length == 0) dr[strSearchAttribName] = "Record Not Found";
                                else
                                {
                                    for (int l = 0; l < drr.Length; l++)
                                    {
                                        if (!sBindDisplayField.Contains("+"))
                                        {
                                            dr[strSearchAttribName] = drr[l][sBindDisplayField].ToString();
                                            dr[strSearchAttribName + "Bind_Storage_Value"] = drr[l][sBindStoreField].ToString();
                                        }
                                        else
                                        {
                                            try
                                            {
                                                dr[strSearchAttribName] = drr[l]["Column1"].ToString();
                                            }
                                            catch { dr[strSearchAttribName] = ""; }

                                        }
                                    }
                                }
                            }
                        }
                        dt.Dispose();
                        dt = null;
                    }
                }
            }
        }
        gp = null;
    }

    private string getDistinctCategoryQuery(DataTable dtaPage, DataTable dtaPageKeys, DataTable dtaPageSrch, DataTable dtaPageControls, ref Hashtable hsDatatype, string order, ref string sFieldAlias, HtmlForm frmObj, string sQuickSearch, ref bool bIsCombinedOrderBy, string sOrderby, ref string sCombinedOrderBy, string groupingField ,ref string CategoryTotalRecordCount,bool ApplyPaging)
    {
        GenerateGrid objGG = new GenerateGrid();
        GridPaging gpobj = new GridPaging();
        string strselectsql = "";
        string iTotalRecord = "0";
        string strKeyvalues = "";
        string Condstr = "";
        string strTableNames = objGG.GetTableNames(dtaPage, dtaPageSrch);
        string currentTotalRecordval = "0";
        string strPageId = "";

        strPageId = dtaPage.Rows[0]["page_id"].ToString();

        if (strTableNames != "")
        {
            SecurityFilter objSec = new SecurityFilter();
            string sAFAdmin = objSec.QueryForAFAdmin();
            //-----------Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
            HDDatabase HDD = new HDDatabase();
            string modelConString = "";
            modelConString = HttpContext.Current.Session["servercon"].ToString();
            string str_OwnerId = "";
            string str_BusinessUnit = "";
            if (HttpContext.Current.Session["dbcon"].ToString() != modelConString && sAFAdmin != "")
            {
                BusinessUnit.Access ACS = new BusinessUnit.Access(HttpContext.Current.Session["userid"].ToString(), HDD.GetConnection().ConnectionString, dtaPage.Rows[0]["page_id"].ToString());
                str_OwnerId = ACS.AccessableOwners;
                str_BusinessUnit = ACS.AccessableBuUnits;
            }
            string sCustodianFilter = ""; // = objSec.QueryForCustodianFilter();
            //----------------End for Org Security------------------
            if (sCustodianFilter.Trim() != "")
                if (!sCustodianFilter.StartsWith("or"))
                {
                    if (sAFAdmin.Trim() != "")
                    {
                        sAFAdmin = "(" + sAFAdmin + " and " + sCustodianFilter + ") ";
                    }
                    else
                    {
                        sAFAdmin = "(" + sCustodianFilter + ") ";
                    }
                }
                else
                {
                   if (sAFAdmin.Trim() != "")
                    {
                        sAFAdmin = "(" + sAFAdmin + " " + sCustodianFilter + ") ";
                    }
                    else
                    {
                        sAFAdmin = "(" + sCustodianFilter + ") ";
                    }

                }
            objSec = null;
            if (!ApplyPaging)
                iTotalRecord = getDistinctTotalRecordsToFetch(strTableNames, Condstr, strPageId, groupingField); // Added By Dhanapal On Jan 28 2011
            else
                iTotalRecord = CategoryTotalRecordCount;
            #region Old Lines commented by 'Imran Gani' on 14-Mar-2014, to avoid top key from query and use ROW_NUMBER().
            ////strselectsql = GetSelectPageFields(dtaPage, dtaPageSrch, dtaPageControls, strChildField, ref sFieldAliases, "CHILD", ref hsDatatype, strParentField);
            //strselectsql = "Distinct Top " + iTotalRecord + "isnull( [" + strPageId + "]" + "." + "[" + groupingField + "] ,'' ) as " + groupingField+ " ";
            #endregion
            strselectsql = "Distinct isnull( [" + strPageId + "]" + "." + "[" + groupingField + "] ,'' ) as " + groupingField + " ";
            strKeyvalues = objGG.GetKeyValues(dtaPage, dtaPageSrch, dtaPageKeys);

            Condstr = " [" + strPageId + "]" + "." + "[" + groupingField + "]" + " is not null";

            if (dtaPageControls.Select("control_attrib_id='modified_at'").Length > 0)
            {
                sOrderby = "modified_at";
            }
            else
            {
                if (dtaPageControls.Select("control_attrib_id='modified_date'").Length > 0)
                    sOrderby = "modified_date";

            }
            strselectsql += ", " + sOrderby;

            sFieldAlias = groupingField + "," + sOrderby;

            CategoryTotalRecordCount = iTotalRecord.ToString();

            if (strselectsql != "")
            {
                #region Old Lines commented by 'Imran Gani' on 14-Mar-2014, to avoid top key from query and use ROW_NUMBER().
                //if (strKeyvalues != "")
                //{
                //    //strselectsql = "select Top " + iTotalRecord.ToString() + " " + strKeyvalues + " keys, " + "  " + strselectsql + " from " + strTableNames;
                //    //strselectsql = "select Top " + currentTotalRecordval.ToString() + " " + strKeyvalues + " keys, " + "  " + strselectsql + " from " + strTableNames;
                //    strselectsql = "select " + strselectsql + ",  " + strKeyvalues + " keys " + "  " + " from " + strTableNames;
                //}
                //else
                //{
                //    strselectsql = "select " + strselectsql + " from " + strTableNames;
                //}
                #endregion

                if (strKeyvalues != "") // Added by 'Imran Gani' on 14-Mar-2014, to use ROW_NUMBER() key in query.
                    strselectsql = "select " + strselectsql + ",  " + strKeyvalues + " keys, ROW_NUMBER() OVER (ORDER BY " + sOrderby + " desc, " + strKeyvalues + " asc) AS [row] from " + strTableNames;
                else
                    strselectsql = "select " + strselectsql + ", ROW_NUMBER() OVER (ORDER BY " + sOrderby + " desc) AS [row] from " + strTableNames;

                //-----------Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
                string str_OrgSecurity = "";
                if (str_OwnerId != "" && dtaPageControls.Select("control_id='owner_id' or control_attrib_id='owner_id'").Length > 0)
                {
                    str_OrgSecurity += " " + str_OwnerId.Remove(0, 5) + " ";
                }
                str_OrgSecurity += (str_OrgSecurity == "" ? "" : " or owner_id is null ");
                if (str_BusinessUnit != "" && dtaPageControls.Select("control_id='bu_id' or control_attrib_id='bu_id'").Length > 0)
                {
                    str_OrgSecurity += " " + str_BusinessUnit + " ";
                }
                //----------------End for Org Security------------------
                
                if (sAFAdmin != "")
                {
                    if (dtaPage != null && dtaPage.Rows[0]["page_id"].ToString() == "p_sy_report") // Added by 'Imran Gani' on 01-Feb-2013, for report security per role.
                        strselectsql += " where (" + sAFAdmin + " and " + str_OrgSecurity + " or [" + dtaPage.Rows[0]["page_id"].ToString() + "].[af_row_id] in (select report_id from sy_report_acc where role_id = '" + HttpContext.Current.Session["roleid"] + "' and [is_accessible]=1 ))";
                    else
                        strselectsql += " where (" + sAFAdmin + " and " + str_OrgSecurity + ")";
                    //strselectsql += " where " + sAFAdmin; // commented by 'Imran Gani' on 05-June-2013 for Org Security
                }

                else
                {
                    if (dtaPage != null && dtaPage.Rows[0]["page_id"].ToString() == "p_sy_report") // Added by 'Imran Gani' on 01-Feb-2013, for report security per role.
                        strselectsql += " where (1=1 " + (str_OrgSecurity == "" ? "" : " and (" + str_OrgSecurity + ")") + " or [" + dtaPage.Rows[0]["page_id"].ToString() + "].[af_row_id] in (select report_id from sy_report_acc where role_id = '" + HttpContext.Current.Session["roleid"] + "' and [is_accessible]=1 ))";
                    else
                        strselectsql += " where 1=1 " + (str_OrgSecurity == "" ? "" : " and (" + str_OrgSecurity + ")");
                    //strselectsql += " where 1=1 "; // commented by 'Imran Gani' on 05-June-2013 for Org Security
                }

                if (Condstr != "")
                    //strselectsql += " and " + Condstr;
                    if (dtaPage != null && dtaPage.Rows[0]["page_id"].ToString() == "p_sy_report") // Added by 'Imran Gani' on 01-Feb-2013, for report security per role.
                        strselectsql += " and " + sOrderby + " in (select Max(" + strPageId + "." + sOrderby + ") From " + strTableNames + " where (1=1 " + (sAFAdmin == "" ? "" : " and " + sAFAdmin) + (str_OrgSecurity == "" ? "" : " and " + str_OrgSecurity) + " or [" + dtaPage.Rows[0]["page_id"].ToString() + "].[af_row_id] in (select report_id from sy_report_acc where role_id = '" + HttpContext.Current.Session["roleid"] + "' and [is_accessible]=1 )) Group By isnull(" + strPageId + "." + groupingField + ",'' ))";
                    else
                        strselectsql += " and " + sOrderby + " in (select Max(" + strPageId + "." + sOrderby + ") From " + strTableNames + " where (1=1 " + (sAFAdmin == "" ? "" : " and " + sAFAdmin) + (str_OrgSecurity == "" ? "" : " and " + str_OrgSecurity) + ") Group By isnull(" + strPageId + "." + groupingField + ",'' ))";
                //strselectsql += " and " + sOrderby + " in (select Max(" + strPageId + "." + sOrderby + ") From " + strTableNames + " Group By isnull(" + strPageId + "." + groupingField + ",'' ))"; // commented by 'Imran Gani' on 05-June-2013 for Org Security

                       // and modified_at IN (SELECT Max(modified_at) FROM [bu_childpage] GROUP BY userval)

            }

        }
        return strselectsql;
    }


    private string getDistinctTotalRecordsToFetch(string strTableName, string Condstr ,string strPageId , string groupField)
    {
        HDD = new HDDatabase();
        string strSqlQuery = "";
        string strDistinctQuery = "";
        string iTotalRecords = "0";
        //strDistinctQuery = "Select distinct " + groupField + " from " + strTableName + " where " + "[" + strPageId + "]" + "." + "[" + groupField + "]" + " is not null or" + "[" + strPageId + "]" + "." + "[" + groupField + "]" + " <> '' ";
        strDistinctQuery = "Select distinct isnull (" + groupField + ",'') as " + groupField + " from " + strTableName;
        strSqlQuery = "Select count(*) from " + " ( " + strDistinctQuery + " ) DistinctTable ";
        //return strSqlQuery;
        try
        {
            DataSet dsTemp = HDD.GetDataset(strSqlQuery);
            HDD = null;
            if (dsTemp.Tables.Count > 0)
            {
                if (dsTemp.Tables[0].Rows.Count > 0)
                {
                    iTotalRecords = dsTemp.Tables[0].Rows[0][0].ToString();
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in CategoryView Total Record Fetch.");
        }
        return iTotalRecords.ToString();
    }

    private void BuildCategoryHeader(DataSet dseObj, DataTable dtaPage, DataTable dtaPageSrch, DataTable dtaPageKeys, DataTable dtaPageControls, HtmlForm frmObj, bool bRead, bool bCreate, bool bEdit, bool bDelete, string groupingField, string sOrderby, string Order, string strPagesetRowId, DataSet dsePageObj ,string pagingDetails)
    {
        string strgroupDisplayField = "";
        string strgroupStorageField = "";
        System.Web.UI.HtmlControls.HtmlGenericControl categoryTotalContainer = (System.Web.UI.HtmlControls.HtmlGenericControl)DDI.FindControl(frmObj.Controls, "panelDynamicCategory");
        GenerateGrid objGG = new GenerateGrid();
        Panel categoryContainer = new Panel();
        categoryContainer.ID = "CATEGORY_CONTAINER";

        string strMenuRowId = "";
        if (frmObj.Page.Request.QueryString["mn"].ToString() != null)
        {
            strMenuRowId = frmObj.Page.Request.QueryString["mn"].ToString();
        }
        HiddenField hfEditPageValue = (HiddenField)DDI.FindControl(frmObj.Controls, "hdnCategoryEditPage");
        string strEditPage = objGG.getEditPage(HDD, strMenuRowId);
        if ( hfEditPageValue != null )
            hfEditPageValue.Value = strEditPage;

        GenerateGrid objGD = new GenerateGrid(); // Added by 'Imran Gani' on 09-Aug-12, for currency conversion.
        objGD.loadCurrencySettings(); //To load the Currency Settings
        ArrayList currencyCode_Rate = objGD.currencyCode_Rate;
        
        foreach (DataRow drgroupField in dseObj.Tables[0].Rows)
        {
            if (dseObj.Tables[0].Columns[groupingField + "Bind_Storage_Value"] != null)
            {
                strgroupDisplayField = drgroupField[groupingField].ToString();
                strgroupStorageField = drgroupField[groupingField + "Bind_Storage_Value"].ToString();
            }
            else
            {
                strgroupDisplayField = drgroupField[groupingField].ToString();
                strgroupStorageField = drgroupField[groupingField].ToString();
            }
            GenerateCategoryItems(strgroupDisplayField, strgroupStorageField, frmObj, sOrderby, dseObj, dtaPage, dtaPageSrch, dtaPageKeys, dtaPageControls, groupingField, Order, strPagesetRowId, dsePageObj, bCreate, bEdit, bDelete, categoryContainer, currencyCode_Rate);
        }

        categoryTotalContainer.Controls.Add(categoryContainer);

        Panel p1 = new Panel();
        p1.ID = "CATEGORY_MORE";
        p1.Attributes.Add("class", "Dynamic_PageSectionHeaderRow");
     
        LiteralControl lc = new LiteralControl();
        lc.Text = lc.Text = "<a href=\"javascript:;\" onclick=\"javascript:DemandMoreRecord(this , 'CVH','','','" + pagingDetails + "',true" + ");\">More...</a>";
        p1.Controls.Add(lc);
  
        categoryTotalContainer.Controls.Add(p1);
        

    }

    private void GenerateCategoryItems(string strgroupDisplayField, string strgroupStorageField, HtmlForm frmObj, string sOrderby, DataSet dseObj, DataTable dtaPage, DataTable dtaPageSrch, DataTable dtaPageKeys, DataTable dtaPageControls, string groupingField, string Order, string strPagesetRowId, DataSet dsePageObj, bool bCreate, bool bEdit, bool bDelete, Panel categoryDiv, ArrayList currencyCode_Rate)
    {
        //System.Web.UI.HtmlControls.HtmlGenericControl categoryDiv = (System.Web.UI.HtmlControls.HtmlGenericControl)DDI.FindControl(frmObj.Controls, "panelDynamicCategory");
        string strPageId = "";

        strPageId = dtaPage.Rows[0]["page_id"].ToString();
        
        if (categoryDiv != null)
        {
            Panel p = new Panel();
            p.Style.Add("margin", "0px 0px 10px 0px");
            HtmlTable ht = new HtmlTable();
            if (strgroupStorageField.Trim() == "")
            {
                ht.ID = "CATEGORYNULL_" + "TABLE";
                
            }
            else
            {
                ht.ID = "CATEGORY" + strgroupStorageField + "_" + "TABLE";
            }
            //ht.Border = 1;
            ht.Width = "100%";
            ht.Border = 0;
            ht.CellPadding = 0;
            ht.CellSpacing = 0;

            Panel caption = new Panel();
            caption.Attributes.Add("class" , "Dynamic_PageSectionHeaderRow");
            LiteralControl lc = new LiteralControl();
            DataRow dr = dtaPageControls.Select("control_id='" + groupingField + "'")[0]; // Added by 'Imran Gani' on 09-Aug-12, for currency conversion.
            if (strgroupStorageField.Trim() == "")
            {
                lc.Text = "<B>[--No Category--]</B>";
            }
            else if (dr["control_attrib_type"].ToString() == "CU") // Added by 'Imran Gani' on 09-Aug-12, for currency conversion.
                lc.Text = "<B>" + DDI.manageCurrency(strgroupDisplayField, currencyCode_Rate) + "</B>";
            else
                lc.Text = "<B>" + HttpUtility.HtmlEncode(strgroupDisplayField) + "</B>";
            caption.Controls.Add(lc);
            if (strgroupStorageField.Trim() == "")
            {
                caption.ID = "CATEGORYNULL_" + "CAPTION";
            }
            else
            {
                caption.ID = "CATEGORY" + strgroupStorageField + "_" + "CAPTION";
            }
            p.Controls.Add(caption);

         


            p.Controls.Add(ht);
            getCategoryRowItems(dtaPage, dtaPageKeys, dtaPageSrch, ref  dtaPageControls, frmObj, sOrderby, ref ht, strPageId, strgroupStorageField, groupingField, Order, strPagesetRowId, dsePageObj, bCreate, bEdit, bDelete, currencyCode_Rate);

          
           
            categoryDiv.Controls.Add(p);
        }
    }

    private void getCategoryRowItems(DataTable dtaPage, DataTable dtaPageKeys, DataTable dtaPageSrch, ref DataTable dtaPageControls, HtmlForm frmObj, string sOrderby, ref HtmlTable htCategorytable, string strPageId, string strgroupStorageField, string groupingField, string Order, string strPagesetRowId, DataSet dsePageObj, bool bCreate, bool bEdit, bool bDelete, ArrayList currencyCode_Rate)
    {
        HDD = new HDDatabase();
        Hashtable hsDatatype = new Hashtable();
        TreeViewI tvI = new TreeViewI();
        GenerateGrid objGG = new GenerateGrid();
        string childField = "";
        string sFieldAliases = "";
        bool IsCombinedOrderBy = false;
        string CombinedOrderBy = "";
        string QuickSearchSQL = "";
        string CondStr = "";

        string iPagingDetails = "";

        string iTotalRowFetchCount = "";
        iTotalRowFetchCount = "0";

        CondStr = "isnull([" + strPageId + "]" + "." + "[" + groupingField + "] , '')" + "=" + "'" + strgroupStorageField + "'";
        string strSql = getCategoryRowFetchQuery(dtaPage, dtaPageKeys, dtaPageSrch, ref  dtaPageControls, ref  hsDatatype, CondStr, ref  sFieldAliases, frmObj, QuickSearchSQL, ref  IsCombinedOrderBy, sOrderby, ref  CombinedOrderBy, ref iTotalRowFetchCount ,false);
        strSql += " and " + CondStr;
        #region Old Lines commented by 'Imran Gani' on 14-Mar-2014, to avoid top key from query and use ROW_NUMBER().
        //if (Order.Trim() == "asc")
        //{
        //    strSql = strSql.TrimEnd() + " order by " + sOrderby + " " + " desc" + " ,[keys] desc ";
        //}
        //else
        //{
        //    strSql = strSql.TrimEnd() + " order by " + sOrderby + " " + " asc" + " ,[keys] desc ";
        //}
        //strSql = "Select top " + GlobalValues.intNoOfRecordsPerPage.ToString() + " " + sFieldAliases + " from ( " + strSql + ") as tt order by " + sOrderby + " " + Order + " ,[keys] asc ";
        #endregion
        strSql = "Select " + sFieldAliases + " from ( " + strSql + ") as tt  where [row] between 1 and " + GlobalValues.intNoOfRecordsPerPage + " order by [row] asc";
        DataSet dseObj = tvI.getFinalQueryDataset(dtaPage, dtaPageSrch, strSql, "", "");
        if (dseObj.Tables[0].Rows.Count > 0)
        {
            dseObj.Tables[0].TableName = dtaPage.Rows[0]["page_id"].ToString();
            //objGG.sortData(ref dseObj);
            if (dtaPageKeys.Rows.Count > 0)
                objGG.populateMasterFieldValues(ref dseObj, ref dtaPageSrch, ref dtaPageKeys);

            iPagingDetails = iTotalRowFetchCount + "|" + iTotalRowFetchCount + "|" + GlobalValues.intNoOfRecordsPerPage.ToString() + "|" + "1"; //TOtalCount | currentCount | limitCount | pagno

            BuildCategoryRow(dseObj, strPagesetRowId, frmObj, bCreate, bEdit, bDelete, ref dsePageObj, ref hsDatatype, ref htCategorytable, dtaPage, iPagingDetails, strgroupStorageField, currencyCode_Rate);
        }
        else
        {
            

        }
        
    }

    private void BuildCategoryRow(DataSet dseObj, string strPagesetRowId, HtmlForm frmObj, bool bCreate, bool bEdit, bool bDelete, ref DataSet dsPageInfo, ref Hashtable hsDatatype, ref HtmlTable hta, DataTable dtaPage, string iPagingDetails, string groupingField, ArrayList currencyCode_Rate)
    {
        GenerateGrid obGG = new GenerateGrid();
        security HDS = new security();
        HDD = new HDDatabase();
        bool blnStatus = true;
        bool blnActions = false;
        //int RowCount = obGG.GetRowCount(dseObj); 
        DataRow[] drractions = null;
        DataTable dtaObj = null;
        //HtmlTable hta = new HtmlTable();
       
        string strMenuRowId = "";
        if (frmObj.Page.Request.QueryString["mn"].ToString() != null)
        {
            strMenuRowId = frmObj.Page.Request.QueryString["mn"].ToString();
        }
        blnActions = obGG.CanShowActionButton(ref drractions, dsPageInfo); 
        //HeaderRow(dtaObj, hta, Create, Edit, Delete, hsDatatype, blnActions);
        bool IsAdminConsole = HDS.allRightsForNGMODEL();
        bool bHasChild = obGG.hasChild(ref dsPageInfo);
        CategoryRow(dseObj.Tables[0], strPagesetRowId, hta, strMenuRowId, frmObj, obGG.getEditPage(HDD, strMenuRowId), bCreate, bEdit, bDelete, ref dsPageInfo, ref hsDatatype, IsAdminConsole, bHasChild, blnActions, drractions, iPagingDetails, groupingField, currencyCode_Rate);

    }

    private void CategoryRow(DataTable dtaObj, string strPagesetRowId, HtmlTable htaObj, string strMenuRowId, HtmlForm frmObj, string EditPage, bool Create, bool Edit, bool Delete, ref DataSet dsPageInfo, ref Hashtable hsDatatype, bool IsAdminConsole, bool HasChild, bool blnaction, DataRow[] drractions, string iPagingDetails, string groupingField, ArrayList currencyCode_Rate)
    {

        DDI = new DynamicDisplayI();
        GenerateGrid obGG = new GenerateGrid();
        bool blnStatus = true;
        string strKey = "";
        string strText = "";
        int intCurrentPage = 1;
        string sUTC_Offset= "";
        sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");
     
        bool bEditOverride = true;
        bool bDeleteOverride = false;
        String sEditKeyValues = "";
        String sDeleteKeyValues = "";
        String sEdit_RowId = "";
        String sDelete_RowId = "";
        int ColspanCount = 0;
        int intCurrRowCss = 0;
        

        obGG.getOverrideAccess(ref bEditOverride, ref bDeleteOverride, ref dtaObj, ref sEditKeyValues, ref sDeleteKeyValues, ref sEdit_RowId, ref sDelete_RowId);
        for (int i = 0; i < dtaObj.Rows.Count; i++)
        {
            HtmlTableRow htr = new HtmlTableRow();
            for (int j = 0; j < dtaObj.Columns.Count; j++)
            {
                if ( j > 2 )   // Added By Dhanapal TO Limit The Columns Count By 2
                    continue;
                ColspanCount = dtaObj.Columns.Count;
                HtmlTableCell htc = new HtmlTableCell();
                /********To FIx the Column Width*************/
                if ( j > 1)
                    htc.Width = "30%";
 
                /*******************************************/


                if (dtaObj.Rows[i][j] == System.DBNull.Value)
                    strText = "&nbsp;";
                else
                    strText = HttpUtility.HtmlEncode(dtaObj.Rows[i][j].ToString());
                if (dtaObj.Columns[j].ColumnName.ToLower() == "keys")
                {
                    htr.ID = "CATERGORYAF_ROW_ID _" + strText;
                    strKey = strText;
                    HtmlTableCell htcc = new HtmlTableCell();
                    HtmlTableRow htrr = new HtmlTableRow();

                    #region Old Code commented by 'Imran Gani' on 29-May-2013, to avoid server button for postback control
                    //if (Create || Edit)
                    //{
                    //    if (sEditKeyValues.Contains(strText))
                    //    {
                    //        if (bEditOverride)
                    //        {
                    //            strText = @"" + EditPage + @"?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(strText)
                    //                + "&mn=" + strMenuRowId + @"";
                    //            strText = obGG.addMasterPrimaryKey(strText);
                    //        }
                    //        else
                    //        {
                    //            strText = @"" + "NoAccess.aspx" + @"?pgs_id=" + strPagesetRowId + "&PK=" + sEdit_RowId
                    //                + "&mn=" + strMenuRowId + @"";
                    //        }
                    //    }
                    //    else
                    //    {
                    //        strText = @"" + EditPage + @"?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(strText)
                    //            + "&mn=" + strMenuRowId + @"";
                    //        strText = obGG.addMasterPrimaryKey(strText);
                    //    }

                    //    ImageButton lnkedit = new ImageButton();
                    //    lnkedit.ImageUrl = "images/edit.gif";
                    //    lnkedit.PostBackUrl = strText;
                    //    lnkedit.ToolTip = "Edit";
                    //    lnkedit.CausesValidation = false;
                    //    lnkedit.AlternateText = "Edit";//sanal on Sep 02, 2011 to avoid the display of "Submit Query" in FF
                    //    lnkedit.Attributes.Add("onClick", "javascript:this.src='images/load.gif'");
                    //    if (!IsAdminConsole)
                    //        lnkedit.ID = "E_" + strKey;
                    //    htcc.Width = "25px";

                    //    htcc.Controls.Add(lnkedit);
                    //    htrr.Cells.Add(htcc);
                    //}

                    //if (Create) 
                    //{
                    //    htcc = new HtmlTableCell(); 
                    //    strText = @"" + EditPage + @"?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(strKey)
                    //        + "&mn=" + strMenuRowId + @"&CPY=0";

                    //    strText = obGG.addMasterPrimaryKey(strText);

                    //    ImageButton lnkcopy = new ImageButton();
                    //    lnkcopy.ImageUrl = "images/copy.gif";
                    //    lnkcopy.PostBackUrl = strText;
                    //    lnkcopy.ToolTip = "Copy";
                    //    lnkcopy.CausesValidation = false;
                    //    lnkcopy.AlternateText = "Copy";//sanal on Sep 02, 2011 to avoid the display of "Submit Query" in FF
                    //    lnkcopy.Attributes.Add("onClick", "javascript:this.src='images/load.gif'");
                    //    if (!IsAdminConsole)
                    //        lnkcopy.ID = "C_" + strKey;
                    //    htcc.Width = "25px";
                    //    htcc.Controls.Add(lnkcopy);
                    //    htrr.Cells.Add(htcc);
                    //}
                    #endregion

                    if (Create || Edit)
                    {
                        if (sEditKeyValues.Contains(strText))
                        {
                            if (bEditOverride)
                            {
                                strText = @"" + EditPage + @"?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(strText) + "&mn=" + strMenuRowId + @"";
                                strText = obGG.addMasterPrimaryKey(strText);
                            }
                            else
                                strText = @"" + "NoAccess.aspx" + @"?pgs_id=" + strPagesetRowId + "&PK=" + sEdit_RowId + "&mn=" + strMenuRowId + @"";
                        }
                        else
                        {
                            strText = @"" + EditPage + @"?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(strText) + "&mn=" + strMenuRowId + @"";
                            strText = obGG.addMasterPrimaryKey(strText);
                        }

                        HyperLink lnkedit = new HyperLink();
                        lnkedit.ImageUrl = "images/edit.gif";
                        lnkedit.ToolTip = "Edit";
                        lnkedit.NavigateUrl = strText;
                        //lnkedit.Attributes.Add("onClick", "javascript:this.src='images/load.gif'");
                        if (!IsAdminConsole)
                            lnkedit.ID = "E_" + strKey;
                        lnkedit.Attributes.Add("onClick", "javascript:$('#ctl00_ContentPlaceHolder3_" + lnkedit.ID + "').find('img').attr('src', 'images/load.gif');");
                        htcc.Controls.Add(lnkedit);
                        htcc.Width = "25px";
                        htrr.Cells.Add(htcc);
                    }

                    if (Create)
                    {
                        htcc = new HtmlTableCell();
                        strText = @"" + EditPage + @"?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(strKey) + "&mn=" + strMenuRowId + @"&CPY=0";
                        strText = obGG.addMasterPrimaryKey(strText);

                        HyperLink lnkcopy = new HyperLink();
                        lnkcopy.ImageUrl = "images/copy.gif";
                        lnkcopy.ToolTip = "Copy";
                        lnkcopy.NavigateUrl = strText;
                        //lnkcopy.Attributes.Add("onClick", "javascript:this.src='images/load.gif'");
                        if (!IsAdminConsole)
                            lnkcopy.ID = "C_" + strKey;
                        lnkcopy.Attributes.Add("onClick", "javascript:$('#ctl00_ContentPlaceHolder3_" + lnkcopy.ID + "').find('img').attr('src', 'images/load.gif');");
                        htcc.Controls.Add(lnkcopy);
                        htcc.Width = "25px";
                        htrr.Cells.Add(htcc);
                    }

                    if (Delete)
                    {
                        htcc = new HtmlTableCell();
                        strText = "<a style='color:Blue;' ><u>Delete</u></a>";
                        string sTemp = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf('/'));
                        sTemp = sTemp + HttpContext.Current.Request.Url.AbsolutePath.Substring(HttpContext.Current.Request.Url.AbsolutePath.LastIndexOf("/"), (HttpContext.Current.Request.Url.AbsolutePath.Length - HttpContext.Current.Request.Url.AbsolutePath.LastIndexOf("/")));
                        sTemp = sTemp + "?pgs_id=" + strPagesetRowId + "&DPK=" + strKey + "&mn=" + strMenuRowId + "&cp=" + intCurrentPage;
                        sTemp = obGG.addMasterPrimaryKey(sTemp);

                        //Label lnkDelete = new Label();
                        ImageButton lnkDelete = new ImageButton();
                        lnkDelete.ImageUrl = "images/delete.gif";
                        //lnkDelete.Text = "Delete";
                        //lnkDelete.CssClass = "SearchPopup";
                        lnkDelete.ToolTip = "Delete";
                        lnkDelete.AlternateText = "Delete";//sanal on Sep 02, 2011 to avoid the display of "Submit Query" in FF
                        //lnkDelete.Click += new ImageClickEventHandler(lnkDelete_Click);

                        //string deleteURLChild = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?\r Note: Child records will also be deleted."")){window.location.href=(""" + sTemp + @"""); DeleteClick('" + strKey + "','" + intCurrentPage + "');}else{return false;};";
                        //string deleteURL = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?"")){window.location.href=(""" + sTemp + @"""); DeleteClick('" + strKey + "','" + intCurrentPage + "');}else{return false;};";//@"javascript:return confirm(""Are you sure you want to delete '" + dtaObj.Rows[i][0].ToString() + @"' ?"")"; 
                        string deleteURLChild = "";
                        string deleteURL = "";
                        if (sDeleteKeyValues.Contains(strKey))
                        {
                            deleteURLChild = @"javascript:if(confirm(""Are you sure you want to delete '" + obGG.includeJavascriptEscapes(HttpUtility.HtmlEncode(dtaObj.Rows[i][1].ToString())) + @"' ?\r Note: Child records will also be deleted."")){ alert('Hello AM Good--','" + strPagesetRowId + "'); }else{return false;};";
                            deleteURL = @"javascript:if(confirm(""Are you sure you want to delete '" + obGG.includeJavascriptEscapes(HttpUtility.HtmlEncode(dtaObj.Rows[i][1].ToString())) + @"' ?\r Note: Child records will also be deleted."")){ alert('Hello AM Good--','" + strPagesetRowId + "'); }else{return false;};";
                          /*  if (bDeleteOverride)
                            {
                                if (HttpContext.Current.Request.QueryString["PK"] != null)
                                {
                                    deleteURLChild = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?\r Note: Child records will also be deleted."")){DeleteClick('" + strKey + "','" + intCurrentPage + "');UpdateMK('" + HttpContext.Current.Request.QueryString["PK"].ToString() + "'); UpdateDeletePageset('" + strPagesetRowId + "'); }else{return false;};";
                                    deleteURL = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?"")){DeleteClick('" + strKey + "','" + intCurrentPage + "'); UpdateMK('" + HttpContext.Current.Request.QueryString["PK"].ToString() + "'); UpdateDeletePageset('" + strPagesetRowId + "');}else{return false;};";//@"javascript:return confirm(""Are you sure you want to delete '" + dtaObj.Rows[i][0].ToString() + @"' ?"")"; 
                                }
                                else
                                {
                                    deleteURLChild = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?\r Note: Child records will also be deleted."")){DeleteClick('" + strKey + "','" + intCurrentPage + "');}else{return false;};";
                                    deleteURL = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?"")){DeleteClick('" + strKey + "','" + intCurrentPage + "');}else{return false;};";//@"javascript:return confirm(""Are you sure you want to delete '" + dtaObj.Rows[i][0].ToString() + @"' ?"")"; 
                                }
                            }
                            else
                            {
                                deleteURLChild = @"javascript:alert(""" + includeJavascriptEscapes(sDelete_RowId) + @""");return false;";
                                deleteURL = @"javascript:alert(""" + includeJavascriptEscapes(sDelete_RowId) + @""");return false;";
                            }*/
                        }
                        else
                        {
                            deleteURLChild = @"javascript:if(confirm(""Are you sure you want to delete '" + obGG.includeJavascriptEscapes(HttpUtility.HtmlEncode(dtaObj.Rows[i][1].ToString())) + @"' ?\r Note: Child records will also be deleted."")){ alert('Hello AM Good--','" + strPagesetRowId + "'); }else{return false;};";
                            deleteURL = @"javascript:if(confirm(""Are you sure you want to delete '" + obGG.includeJavascriptEscapes(HttpUtility.HtmlEncode(dtaObj.Rows[i][1].ToString())) + @"' ?\r Note: Child records will also be deleted."")){ alert('Hello AM Good--','" + strPagesetRowId + "'); }else{return false;};";
                           /* if (HttpContext.Current.Request.QueryString["PK"] != null)
                            {
                                deleteURLChild = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?\r Note: Child records will also be deleted."")){DeleteClick('" + strKey + "','" + intCurrentPage + "');UpdateMK('" + HttpContext.Current.Request.QueryString["PK"].ToString() + "'); UpdateDeletePageset('" + strPagesetRowId + "'); }else{return false;};";
                                deleteURL = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?"")){DeleteClick('" + strKey + "','" + intCurrentPage + "'); UpdateMK('" + HttpContext.Current.Request.QueryString["PK"].ToString() + "'); UpdateDeletePageset('" + strPagesetRowId + "');}else{return false;};";//@"javascript:return confirm(""Are you sure you want to delete '" + dtaObj.Rows[i][0].ToString() + @"' ?"")"; 
                            }
                            else
                            {
                                deleteURLChild = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?\r Note: Child records will also be deleted."")){DeleteClick('" + strKey + "','" + intCurrentPage + "');}else{return false;};";
                                deleteURL = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?"")){DeleteClick('" + strKey + "','" + intCurrentPage + "');}else{return false;};";//@"javascript:return confirm(""Are you sure you want to delete '" + dtaObj.Rows[i][0].ToString() + @"' ?"")"; 
                            }*/
                        }


                       
                        string strImage = "";

                        if (!IsAdminConsole)
                            lnkDelete.ID = "D_" + strKey;

                        if (HasChild)

                            //lnkDelete.Attributes.Add("onClick", "this.src='images/load.gif'; " + deleteURLChild + "");
                            //lnkDelete.OnClientClick = deleteURLChild;
                            strImage = "<a href='javascript:;' onclick=\" DeleteCategoryRow(this,'" + obGG.includeJavascriptEscapes(HttpUtility.HtmlEncode(dtaObj.Rows[i][1].ToString())) + "','" + strKey + "','" + strPagesetRowId + "','Img_" + strKey + "_Id'" + "); \"><img border=0 style='cursor:pointer' id = 'Img_" + strKey + "_Id'  title='Delete'  src='images/Delete.gif'></a>"; 
                        else
                            strImage = "<a href='javascript:;' onclick=\" DeleteCategoryRow(this,'" + obGG.includeJavascriptEscapes(HttpUtility.HtmlEncode(dtaObj.Rows[i][1].ToString())) + "','" + strKey + "','" + strPagesetRowId + "','Img_" + strKey + "_Id'" + "); \"><img border=0 style='cursor:pointer' id = 'Img_" + strKey + "_Id'  title='Delete'  src='images/Delete.gif'></a>"; 
                            //strImage = "<a href='javascript:;' onclick=\" DeleteCategoryRow(this,'" + obGG.includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + "','" + strKey + "','" + strPagesetRowId + "','Img_" + strKey + "_Id'" + "); \"><img border=0 style='cursor:pointer' id = 'Img_" + strKey + "_Id'  title='Delete' onclick=\"javascript:this.src='images/load.gif'\" src='images/Delete.gif'></a>"; 
                            //lnkDelete.Attributes.Add("onClick", "this.src='images/load.gif'; " + deleteURL + "");
                            //strImage = "<a href='javascript:;' onclick=\" DeleteCategoryRow(this,'" + obGG.includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + "','" + strKey + "','" + strPagesetRowId + "'" + "); \"><img border=0 style='cursor:pointer'  title='Delete' onclick=\"javascript:this.src='images/load.gif'\" src='images/Delete.gif'></a>"; 
                           // lnkDelete.OnClientClick = deleteURL;

                        LiteralControl lcdelete = new LiteralControl();
                        lcdelete.Text = strImage;


                        htcc.Controls.Add(lcdelete);
                        htcc.Width = "25px";
                        htrr.Cells.Add(htcc);

                    }

                    if (blnaction) 
                    {
                        htcc = new HtmlTableCell();

                        ImageButton imgaction = new ImageButton();
                        imgaction.ImageUrl = "images/action_16.gif";
                        imgaction.ID = "Ac_"+ strKey;
                        htcc.Controls.Add(imgaction);
                        Action ac = new Action();
                        htcc.Controls.Add(new LiteralControl("<br/>"));
                        ac.CreateActionDIV(ref htcc, drractions, imgaction.ID,strKey,false);
                        htcc.Width = "25px";
                        htrr.Controls.Add(htcc);
                    }

                    HtmlTable htt = new HtmlTable();
                    htt.Border = 0;
                    htt.CellSpacing = 0;
                    htt.CellPadding = 0;
                    htt.Rows.Add(htrr);
                    htc.Controls.Add(htt);
                    htc.Align = "left";
                    if (htrr.Cells.Count == 1)
                        htc.Width = "30px";
                    else if (htrr.Cells.Count == 2)
                        htc.Width = "55px";
                    else if (htrr.Cells.Count == 3)
                        htc.Width = "80px";
                    else if (htrr.Cells.Count == 4)
                        htc.Width = "105px";
                    if (htrr.Cells.Count != 0)
                        htr.Cells.Add(htc);
                }
                else
                {
                    if (hsDatatype.Contains(dtaObj.Columns[j].ColumnName))
                    {
                        #region Old Code commented by 'Imran Gani' on 28-Feb-2014, to avoid 'if' statement and to use switch case.
                        //if (hsDatatype[dtaObj.Columns[j].ColumnName].ToString().ToLower() == "dt")
                        //{
                        //    if (dtaObj.Columns[j].ColumnName.ToLower().Trim() == "modified at" || dtaObj.Columns[j].ColumnName.ToLower().Trim() =="created at")
                        //    {
                        //        if (strText != "" && strText != "&nbsp;")
                        //        {
                        //            if (strText != "" && strText != "&nbsp;")
                        //            {
                        //                strText = DDI.getUsersDT(strText, sUTC_Offset);
                        //                Localization loc = new Localization();

                        //                strText = loc.getDateTime4TimeZone(strText, sUTC_Offset, false, true);
                        //            }
                        //        }
                        //    }
                        //    else
                        //    {
                        //        if (strText != "" && strText != "&nbsp;")
                        //            if (strText != "" && strText != "&nbsp;")
                        //                strText = DDI.getUsersDT(strText, sUTC_Offset);
                        //    }
                        //}

                        //else if (hsDatatype[dtaObj.Columns[j].ColumnName].ToString().ToLower() == "cu")//sanal
                        //{
                        //    if (strText != "&nbsp;")
                        //        strText = DDI.manageCurrency(strText, currencyCode_Rate);
                        //}
                        //else if (hsDatatype[dtaObj.Columns[j].ColumnName].ToString().ToLower() == "da")
                        //{
                        //    if (strText != "" && strText != "&nbsp;")
                        //        strText = obGG.manageDateTimeValues("da", strText);
                        //}
                        #region MyRegion
                        //if (hsDatatype[dtaObj.Columns[j].ColumnName].ToString().ToLower() == "dt")
                        //{
                        //    if (strText != "" && strText != "&nbsp;")
                        //        strText = DDI.getUsersDT(strText, sUTC_Offset);
                        //}
                        //else if (hsDatatype[dtaObj.Columns[j].ColumnName].ToString().ToLower() == "cu")//sanal
                        //    strText = DDI.manageCurrency(strText, currencyCode_Rate);
                        //else if (hsDatatype[dtaObj.Columns[j].ColumnName].ToString().ToLower() == "da")
                        //    strText = manageDateTimeValues("da", strText);
                        //if (strText.IndexOf(" ") != -1)
                        //    strText = DateTime.Parse(strText.Substring(0, strText.IndexOf(" "))).ToString("dd-MMM-yyyy"); ; 
                        #endregion
                        #endregion

                        #region New code Added by 'Imran Gani' on 28-Feb-2014, to use switch case with MBLocale
                        Localization loc = new Localization();
                        strText = loc.getLocaleFormattedValue(strText, hsDatatype[dtaObj.Columns[j].ColumnName].ToString(), dtaObj.Columns[j].ColumnName, sUTC_Offset, DDI, currencyCode_Rate);
                        loc = null;
                        #endregion
                    }

                    if (j == 1 && dtaObj.Columns.Contains("keys"))
                    {
                        #region MyRegion 
                        //string sViewPage = @"<a href=""DynamicScreen.aspx?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(dtaObj.Rows[i]["keys"].ToString())
                        //            + "&mn=" + strMenuRowId + @"&VMODE=1""><font color=""blue"">" + strText + "</font></a>";
                        //if (EditPage.ToLower() == "reportwizard.aspx")
                        //    sViewPage = @"<a href=""Report.aspx?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(dtaObj.Rows[i]["keys"].ToString())
                        //+ "&mn=" + strMenuRowId + @"&VMODE=1"" target=""_blank""><font face=""Arial"" color=""blue"">" + strText + "</font></a>";
                        //strText = @"<a href=""" + sViewPage + "?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(dtaObj.Rows[i]["keys"].ToString())
                        //+ "&mn=" + strMenuRowId + @"&VMODE=1""><font color=""blue"">" + strText + "</font></a>"; 
                        #endregion
                        if (strText.Trim() == "")
                            strText = "&nbsp;";
                        string sViewPage = @"<a href=""" + EditPage + "?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(dtaObj.Rows[i]["keys"].ToString()) + "&MK=" + HttpContext.Current.Request.QueryString["PK"] + @""
                            + "&mn=" + strMenuRowId + @"&VMODE=1""><font color=""blue"">" + strText + "</font></a>";
                        //strText = "&nbsp;" + sViewPage;
                        strText = sViewPage; 
                    }
                    obGG.handleControlType(ref strText, ref dsPageInfo, ref dtaObj, j, i);
                    //htc.Controls.Add(new LiteralControl("&nbsp;" + strText + "&nbsp;"));
                    htc.Controls.Add(new LiteralControl(strText)); 

                    obGG.setAlignment(ref htc, hsDatatype[dtaObj.Columns[j].ColumnName].ToString());
                    htr.Cells.Add(htc);
                }
                int intRow = (htaObj.Rows.Count + 1) % 2;
                intCurrRowCss = intRow;
                htr.VAlign = "middle";
                htr.Height = "25px"; 
                htr.Attributes.Add("Class", "Grid_Row" + intRow.ToString());
                htr.Attributes.Add("onMouseOver", "this.className='Grid_Scroll_BG'");
                htr.Attributes.Add("onMouseOut", "this.className='" + "Grid_Row" + intRow.ToString() + "'");
                
                htaObj.Rows.Add(htr);
            }
            obGG.addstyles(ref htr);
        }
        //htaObj.Rows[0].Cells[0].ColSpan = ColspanCount; //To dynamically assign Colspan count
        htaObj.Border = 0;

        

        HtmlTableRow htrn = new HtmlTableRow();
       

        Panel p = new Panel();
      
        p.Attributes.Add("class", "CategoryMoreDiv");
        LiteralControl lc = new LiteralControl();

        string idConcatValue = groupingField;
        if (groupingField.Trim() == "")
        {
            idConcatValue = "NULL";

        }
       
        //lc.Text = "<a href=\"javascript:;\" onclick=\"javascript:DemandMoreRecord(this , 'CVI','" + "CATEGORY" + groupingField + "_" + "','" + groupingField + "','" + iPagingDetails + "',true" + ");\"><font color=\"blue\">More...  (" + iPagingDetails + "---" + htaObj.ID + ")</font></a>";
        lc.Text = "<a href=\"javascript:;\" onclick=\"javascript:DemandMoreRecord(this , 'CVI','" + "CATEGORY" + idConcatValue + "_" + "','" + groupingField + "','" + iPagingDetails + "',true" + ");\"><font color=\"blue\">More...</font></a>";
        p.Controls.Add(lc);
        p.ID = "CATEGORY" + idConcatValue + "_" + "MORE";
        htaObj.Parent.Controls.Add(p);

    
    }

    public string getCategoryRowFetchQuery(DataTable dtaPage, DataTable dtaPageKeys, DataTable dtaPageSrch, ref DataTable dtPageControls, ref Hashtable hsDatatype, string CondStr, ref string FieldAliases, HtmlForm frmObj, string QuickSearchSQL, ref bool IsCombinedOrderBy, string OrderBy, ref string CombinedOrderBy, ref string iTotalRowFetchCount,bool ApplyPaging)
    {
        TreeViewI tvI = new TreeViewI();
        string strPageSql = "";
        try
        {
            GenerateGrid objGG = new GenerateGrid();
            string strTableNames = objGG.GetTableNames(dtaPage, dtaPageSrch);

            if (strTableNames != "")
            {
                SecurityFilter objSec = new SecurityFilter();
                string sAFAdmin = objSec.QueryForAFAdmin();
                //-----------Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
                HDDatabase HDD = new HDDatabase();
                string modelConString = "";
                modelConString = HttpContext.Current.Session["servercon"].ToString();
                string str_OwnerId = "";
                string str_BusinessUnit = "";
                if (HttpContext.Current.Session["dbcon"].ToString() != modelConString && sAFAdmin != "")
                {
                    BusinessUnit.Access ACS = new BusinessUnit.Access(HttpContext.Current.Session["userid"].ToString(), HDD.GetConnection().ConnectionString, dtaPage.Rows[0]["page_id"].ToString());
                    str_OwnerId = ACS.AccessableOwners;
                    str_BusinessUnit = ACS.AccessableBuUnits;
                }
                string sCustodianFilter = ""; // = objSec.QueryForCustodianFilter();
                //----------------End for Org Security------------------
                if (sCustodianFilter.Trim() != "")
                    if (!sCustodianFilter.StartsWith("or"))
                    {
                        if (sAFAdmin.Trim() != "")
                        {
                            sAFAdmin = "(" + sAFAdmin + " and " + sCustodianFilter + ") ";
                        }
                        else
                        {
                            sAFAdmin = "(" + sCustodianFilter + ") ";
                        }
                    }
                    else
                    {
                        //if (QuickSearchSQL.Trim() == "")  // if no search exists show all no owner records
                        //{
                        if (sAFAdmin.Trim() != "")
                        {
                            sAFAdmin = "(" + sAFAdmin + " " + sCustodianFilter + ") ";
                        }
                        else
                        {
                            sAFAdmin = "(" + sCustodianFilter + ") ";
                        }
                        //sAFAdmin += " " + sCustodianFilter;
                        // }
                    }
                objSec = null;
                string iTotalRecords = "";
                if ( !ApplyPaging )
                    iTotalRecords = tvI.getTotalRecordsToFetch(strTableNames, CondStr);
                else
                    iTotalRecords = iTotalRowFetchCount;

                iTotalRowFetchCount = iTotalRecords.ToString();

                //string iTotalRecords = getTotalRecordsToFetch(strTableNames, sAFAdmin, QuickSearchSQL, frmObj, ref IsCombinedOrderBy, OrderBy);
                string strSelectFlds = objGG.GetSelectFlds(dtaPage, dtaPageSrch, ref hsDatatype, ref FieldAliases, ref dtPageControls, ref CombinedOrderBy, ref OrderBy);
                if (strSelectFlds != "")
                {
                    FieldAliases = "[keys], " + FieldAliases;
                    string strKeyValues = objGG.GetKeyValues(dtaPage, dtaPageSrch, dtaPageKeys);
                    string strJoins = objGG.GetJoins(dtaPage, dtaPageSrch, dtaPageKeys);

                    #region Added by 'Imran Gani' on 14-Mar-2014, to use ROW_NUMBER() key in query.
                    if (strKeyValues != "")
                        strPageSql = "select " + strKeyValues + " keys, " + strSelectFlds + ", ROW_NUMBER() OVER (ORDER BY " + OrderBy + " desc, " + strKeyValues + " asc) AS [row] from " + strTableNames;
                    else
                        strPageSql = "select " + strSelectFlds + ", ROW_NUMBER() OVER (ORDER BY " + OrderBy + " desc) AS [row] from " + strTableNames;
                    #endregion
                    #region Old Lines commented by 'Imran Gani' on 14-Mar-2014, to avoid top key from query and use ROW_NUMBER().
                    //if (strKeyValues != "")
                    //    strPageSql = "select top " + iTotalRecords.ToString() + " " + strKeyValues + " keys, " + strSelectFlds + " from " + strTableNames + "";
                    //else
                    //    strPageSql = "select " + strSelectFlds + " from " + strTableNames + "";

                    /*if (childField.Length > 0)
                                            if (HttpContext.Current.Request["PK"] != null)
                                                strJoins += childField + "='" + HttpContext.Current.Request["PK"].ToString() + "'";*/
                    #endregion
                    //-----------Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
                    string str_OrgSecurity = "";
                    if (str_OwnerId != "" && dtPageControls.Select("control_id='owner_id' or control_attrib_id='owner_id'").Length > 0)
                    {
                        str_OrgSecurity += " " + str_OwnerId.Remove(0, 5) + " ";
                    }
                    str_OrgSecurity += (str_OrgSecurity == "" ? "" : " or owner_id is null ");
                    if (str_BusinessUnit != "" && dtPageControls.Select("control_id='bu_id' or control_attrib_id='bu_id'").Length > 0)
                    {
                        str_OrgSecurity += " " + str_BusinessUnit + " ";
                    }
                    //----------------End for Org Security------------------
                
                    if (sAFAdmin != "")
                    {
                        if (dtaPage != null && dtaPage.Rows[0]["page_id"].ToString() == "p_sy_report") // Added by 'Imran Gani' on 01-Feb-2013, for report security per role.
                            strPageSql += " where (" + sAFAdmin + (str_OrgSecurity == "" ? "" : " and " + str_OrgSecurity) + " or [" + dtaPage.Rows[0]["page_id"].ToString() + "].[af_row_id] in (select report_id from sy_report_acc where role_id = '" + HttpContext.Current.Session["roleid"] + "' and [is_accessible]=1 ))";
                        else
                            strPageSql += " where (" + sAFAdmin + (str_OrgSecurity == "" ? "" : " and " + str_OrgSecurity) + ")";
                        //strPageSql += " where " + sAFAdmin; // commented by 'Imran Gani' on 05-June-2013 for Org Security
                    }
                    else if (strJoins != "")
                    {
                        strPageSql += " where " + strJoins;
                    }
                    else
                    {
                        if (dtaPage != null && dtaPage.Rows[0]["page_id"].ToString() == "p_sy_report") // Added by 'Imran Gani' on 01-Feb-2013, for report security per role.
                            strPageSql += " where (1=1 " + (str_OrgSecurity == "" ? "" : " and " + str_OrgSecurity) + " or [" + dtaPage.Rows[0]["page_id"].ToString() + "].[af_row_id] in (select report_id from sy_report_acc where role_id = '" + HttpContext.Current.Session["roleid"] + "' and [is_accessible]=1 ))";
                        else
                            strPageSql += " where 1=1 " + (str_OrgSecurity == "" ? "" : " and (" + str_OrgSecurity + ")");
                        //strPageSql += " where 1=1 "; // commented by 'Imran Gani' on 05-June-2013 for Org Security
                    }
                }
            }
        }

        catch
        {
        }
        return strPageSql;
        
    }

    public string getCategoryHeaderJSONStr(string strPagesetRowId,string strpagedetails,string strCategorygroupingField)
    {
        PageInfoLoad PIL = new PageInfoLoad();
        DataSet dsePageObj = PIL.GetPageSetPagesSrchInfo(strPagesetRowId);
        DataTable dtaPageSet = dsePageObj.Tables["PageSet"];
        DataTable dtaPage = dsePageObj.Tables["Page"];
        DataTable dtaPageKeys = dsePageObj.Tables["PageKeys"];
        DataTable dtaPageSrch = dsePageObj.Tables["PageSrch"];
        DataTable dtaPageControls = dsePageObj.Tables["Page Controls"];
        DataTable dtaPageMode = dsePageObj.Tables["PageModes"];
        DataTable dtaPageModeFields = dsePageObj.Tables["PageModesFields"];

        string iTotalRecordFetchCount = "0";
        string iCurrentRecordCount = "0";
        string iNoofRecordsLimit = "0";
        string ipageCount = "0";

        string[] pagearrVal = strpagedetails.Split('|');
        Int64 iNewPageCount = 0;
        if (pagearrVal.Length > 0)
        {
            iTotalRecordFetchCount = pagearrVal[0];
            iCurrentRecordCount = pagearrVal[1];
            iNoofRecordsLimit = pagearrVal[2];
            ipageCount = pagearrVal[3];

            iNewPageCount = Convert.ToInt64(ipageCount);
            iNewPageCount = iNewPageCount + 1;

        }
        
        Int64 ICurrentRecordValue = 0;
        if (Convert.ToInt64(iCurrentRecordCount) > Convert.ToInt64(iNoofRecordsLimit))
            ICurrentRecordValue = Convert.ToInt64(iCurrentRecordCount) - Convert.ToInt64(iNoofRecordsLimit);
        else
            return "{\"NORECORD\":\"No Records Available\"}";


        GenerateGrid objGG = new GenerateGrid();
        gp = new GridPaging();

        string strTableNames = objGG.GetTableNames(dtaPage, dtaPageSrch);
        bool bIsCombinedOrderBy = false;//for case 00008760,00008761
        string sCombinedOrderBy = "";//for case 00008760,00008761
        string Order = " desc";
        string sFieldAlias = "";
        string sQuickSearch = "";
        //string sOrderby = gp.getSortField(dtaPageControls, ref Order);
        string sOrderby = "modified_at";
        Hashtable hsDatatype = new Hashtable();
        string CategoryTotalRecordCount = "0";

        CategoryTotalRecordCount = ICurrentRecordValue.ToString();
        
        string strSql = getDistinctCategoryQuery(dtaPage, dtaPageKeys, dtaPageSrch, dtaPageControls, ref hsDatatype, "", ref sFieldAlias, null, sQuickSearch, ref bIsCombinedOrderBy, sOrderby, ref  sCombinedOrderBy, strCategorygroupingField, ref CategoryTotalRecordCount ,true);

        #region Old Lines commented by 'Imran Gani' on 14-Mar-2014, to avoid top key from query and use ROW_NUMBER().
        //if (Order.Trim() == "asc")
        //{
        //    strSql = strSql.TrimEnd() + " order by " + sOrderby + " " + " desc" + " ,[keys] desc ";
        //}
        //else
        //{
        //    strSql = strSql.TrimEnd() + " order by " + sOrderby + " " + " asc" + " ,[keys] desc ";
        //}
        //sFieldAlias += "," + "keys";

        //strSql = "Select top " + GlobalValues.intNoOfRecordsPerPage.ToString() + " " + sFieldAlias + " from ( " + strSql + ") as tt order by " + sOrderby + " " + Order + " ,[keys] asc ";
        ////strSql = "Select top " + GlobalValues.intNoOfRecordsPerPage.ToString() + " " + sFieldAlias + " from ( " + strSql + ") as tt order by " + strCategorygroupingField + " asc";

        ////return "Demo";
        #endregion

        #region Added by 'Imran Gani' on 14-Mar-2014, to use ROW_NUMBER() key in query with starting and ending index.

        int iStartCount = (Int32.Parse(ipageCount) * GlobalValues.intNoOfRecordsPerPage);
        int iEndCount = iStartCount + GlobalValues.intNoOfRecordsPerPage;
        iStartCount++;
        strSql = "Select " + sFieldAlias + ", keys from ( " + strSql + ") as tt where [row] between " + iStartCount + " and " + iEndCount + " order by [row] asc";
        #endregion

        string iRefreshPageDetails = iTotalRecordFetchCount + "|" + ICurrentRecordValue.ToString() + "|" + iNoofRecordsLimit + "|" + iNewPageCount.ToString();

        if (strSql != "")
        {
            try
            {
                HDD = new HDDatabase();
                DataSet dseObj = HDD.GetDataset(strSql);
                if (dseObj.Tables[0].Rows.Count > 0)
                {
                    checkandUpdateDataBindValues(ref dseObj, dtaPage, dtaPageControls, strCategorygroupingField);
                    dseObj.Tables[0].TableName = "DATA";

                    DataTable dtPagedetails = new DataTable();
                    DataColumn dtp = new DataColumn("PAGEDETAILS", typeof(string));
                    dtPagedetails.Columns.Add(dtp);
                    DataColumn dtp1 = new DataColumn("TOTCOUNT", typeof(string));
                    dtPagedetails.Columns.Add(dtp1);

                    DataRow dtrp = dtPagedetails.NewRow();
                    dtrp["PAGEDETAILS"] = iRefreshPageDetails;
                    dtrp["TOTCOUNT"] = iTotalRecordFetchCount;
                    dtPagedetails.Rows.Add(dtrp);


                    dtPagedetails.TableName = "PAGEINFO";
                    
                    
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    DataSet ds = new DataSet();
                    ds.Tables.Add(dseObj.Tables[0].Copy());
                    ds.Tables.Add(dtPagedetails);
                    return js.Serialize(JsonMethods.ToJson(ds)).ToString();
                    
                }
            }
            catch (Exception e)
            {
                LogWriter.WriteLog("Error In Retreiving More Category Header Records.");
            }
        }
        else
        {

        }
        return "";
    }

    public string getCategoryItemsJSONStr(string strPagesetRowId, string strpagedetails, string strCategorygroupingField ,string strCategoryStorageval)
    {
        gp = new GridPaging();
        
        PageInfoLoad PIL = new PageInfoLoad();
        DataSet dsePageObj = PIL.GetPageSetPagesSrchInfo(strPagesetRowId);
        DataTable dtaPageSet = dsePageObj.Tables["PageSet"];
        DataTable dtaPage = dsePageObj.Tables["Page"];
        DataTable dtaPageKeys = dsePageObj.Tables["PageKeys"];
        DataTable dtaPageSrch = dsePageObj.Tables["PageSrch"];
        DataTable dtaPageControls = dsePageObj.Tables["Page Controls"];
        DataTable dtaPageMode = dsePageObj.Tables["PageModes"];
        DataTable dtaPageModeFields = dsePageObj.Tables["PageModesFields"];

        string iTotalRecordFetchCount = "0";
        string iCurrentRecordCount = "0";
        string iNoofRecordsLimit = "0";
        string ipageCount = "0";
        bool Applypaging = false;
        string[] pagearrVal = strpagedetails.Split('|');
        Int64 iNewPageCount = 0;
        if (pagearrVal.Length > 1)
        {
            iTotalRecordFetchCount = pagearrVal[0];
            iCurrentRecordCount = pagearrVal[1];
            iNoofRecordsLimit = pagearrVal[2];
            ipageCount = pagearrVal[3];

            iNewPageCount = Convert.ToInt64(ipageCount);
            iNewPageCount = iNewPageCount + 1;
            Applypaging = true;
        }
        else //Added By Dhanapal For First Load....
        {
            Applypaging = false;
        }

        Int64 ICurrentRecordValue = 0;
        if (Applypaging)
        {
            if (Convert.ToInt64(iCurrentRecordCount) > Convert.ToInt64(iNoofRecordsLimit))
                ICurrentRecordValue = Convert.ToInt64(iCurrentRecordCount) - Convert.ToInt64(iNoofRecordsLimit);
            else
                return "{\"NORECORD\":\"No Records Available\"}";
        }

        string strPageId = "";

        strPageId = dtaPage.Rows[0]["page_id"].ToString();

        string Order = " desc";
        //string sOrderby = gp.getSortField(dtaPageControls, ref Order);
        string sOrderby = "modified_at";
        HDD = new HDDatabase();
        Hashtable hsDatatype = new Hashtable();
        TreeViewI tvI = new TreeViewI();
        GenerateGrid objGG = new GenerateGrid();
        string childField = "";
        string sFieldAliases = "";
        bool IsCombinedOrderBy = false;
        string CombinedOrderBy = "";
        string QuickSearchSQL = "";
        string CondStr = "";

        bool blnActions = false; // Below lines are Added by 'Imran Gani' on 04-June-2012, for Actions button in category view.
        DataRow drAction = null;
        if (dsePageObj.Tables.Contains("Page Actions") && dsePageObj.Tables["Page Actions"] != null)
        {
            if (dsePageObj.Tables["Page Actions"].Rows.Count > 0)
            {
                drAction = dsePageObj.Tables["Page Actions"].Select()[0];
                blnActions = true;
            }
        }

        string iPagingDetails = "";

        string iTotalRowFetchCount = "";
        iTotalRowFetchCount = "0";

        iTotalRowFetchCount = ICurrentRecordValue.ToString();

        CondStr = "isnull([" + strPageId + "]" + "." + "[" + strCategorygroupingField + "],'')" + "=" + "'" + strCategoryStorageval + "'";
        string strSql = getCategoryRowFetchQuery(dtaPage, dtaPageKeys, dtaPageSrch, ref  dtaPageControls, ref  hsDatatype, CondStr, ref  sFieldAliases, null, QuickSearchSQL, ref  IsCombinedOrderBy, sOrderby, ref  CombinedOrderBy, ref iTotalRowFetchCount, Applypaging);
        strSql += " and " + CondStr;
        #region Old Lines commented by 'Imran Gani' on 14-Mar-2014, to avoid top key from query and use ROW_NUMBER().
        //if (Order.Trim() == "asc")
        //{
        //    strSql = strSql.TrimEnd() + " order by " + sOrderby + " " + " desc" + " ,[keys] desc ";
        //}
        //else
        //{
        //    strSql = strSql.TrimEnd() + " order by " + sOrderby + " " + " asc" + " ,[keys] desc ";
        //}
        //strSql = "Select top " + GlobalValues.intNoOfRecordsPerPage.ToString() + " " + sFieldAliases + " from ( " + strSql + ") as tt order by " + sOrderby + " " + Order + " ,[keys] asc ";
        #endregion

        #region Added by 'Imran Gani' on 14-Mar-2014, to use ROW_NUMBER() key in query with starting and ending index.

        int iStartCount = (Int32.Parse(ipageCount) * GlobalValues.intNoOfRecordsPerPage);
        int iEndCount = iStartCount + GlobalValues.intNoOfRecordsPerPage;
        iStartCount++;
        strSql = "Select " + sFieldAliases + " from ( " + strSql + ") as tt  where [row] between " + iStartCount + " and " + iEndCount + " order by [row] asc";
        #endregion
        DataSet dseObj = tvI.getFinalQueryDataset(dtaPage, dtaPageSrch, strSql, "", "");
        if (dseObj.Tables[0].Rows.Count > 0)
        {
            dseObj.Tables[0].TableName = dtaPage.Rows[0]["page_id"].ToString();
            //objGG.sortData(ref dseObj);
            if (dtaPageKeys.Rows.Count > 0)
                objGG.populateMasterFieldValues(ref dseObj, ref dtaPageSrch, ref dtaPageKeys);

            if ( Applypaging )
                iPagingDetails = iTotalRecordFetchCount + "|" + ICurrentRecordValue.ToString() + "|" + iNoofRecordsLimit + "|" + iNewPageCount.ToString(); //TOtalCount | currentCount | limitCount | pagno
            else
                iPagingDetails = iTotalRowFetchCount + "|" + iTotalRowFetchCount + "|" + GlobalValues.intNoOfRecordsPerPage.ToString() + "|" + "1"; //TOtalCount | currentCount | limitCount | pagno

            dseObj.Tables[0].TableName = "DATA";

            DataTable dtPagedetails = new DataTable();
            DataColumn dtp = new DataColumn("PAGEDETAILS", typeof(string));
            dtPagedetails.Columns.Add(dtp);
            DataColumn dtp1 = new DataColumn("TOTCOUNT", typeof(string));
            dtPagedetails.Columns.Add(dtp1);
            DataRow dtrp = dtPagedetails.NewRow();
            dtrp["PAGEDETAILS"] = iPagingDetails;
            dtrp["TOTCOUNT"] = iTotalRecordFetchCount;
            dtPagedetails.Rows.Add(dtrp);

         

            dtPagedetails.TableName = "PAGEINFO";

            DataTable dtDataType = new DataTable();
            dtDataType = getDataTypeTable(hsDatatype, dseObj.Tables[0]);
            dtDataType.TableName = "SCHEMA";

            DataTable dtActionBtn = new DataTable(); // Below DataTable are Added by 'Imran Gani' on 04-June-2012, for Action Button details.
            if (blnActions) 
            {
                dtActionBtn.Columns.Add("name", typeof(string));
                dtActionBtn.Columns.Add("dsc", typeof(string));
                dtActionBtn.Columns.Add("url", typeof(string));

                dtActionBtn.Rows.Add(drAction["name"].ToString(), drAction["description"].ToString(), drAction["target_url"].ToString());
                dtActionBtn.TableName = "ACTION";
            }

            JavaScriptSerializer js = new JavaScriptSerializer();
            DataSet dsresponse = new DataSet();
            dsresponse.Tables.Add(dseObj.Tables[0].Copy());
            dsresponse.Tables.Add(dtDataType);
            dsresponse.Tables.Add(dtPagedetails);
            if (blnActions) dsresponse.Tables.Add(dtActionBtn); // Added by 'Imran Gani' on 04-June-2012, for Action Button.
            return js.Serialize(JsonMethods.ToJson(dsresponse)).ToString();
        }
        return "";
    }

   public DataTable getDataTypeTable(Hashtable hsDataType, DataTable dtObj)
    {
        DataTable dtDataType = new DataTable();
        DataColumn dcDataType1 = new DataColumn("CNAME",typeof(string));
        DataColumn dcDataType2 = new DataColumn("DTYPE", typeof(string));
        dtDataType.Columns.Add(dcDataType1);
        dtDataType.Columns.Add(dcDataType2);
        foreach (DataColumn dc in dtObj.Columns)
        {
            DataRow drDataType = dtDataType.NewRow();
            string strColname = dc.ColumnName;
            string datatype = hsDataType[strColname] != null ? hsDataType[strColname].ToString() : "TX";
            drDataType["CNAME"] = strColname;
            drDataType["DTYPE"] = datatype;
            dtDataType.Rows.Add(drDataType);
        }
        return dtDataType;
    }

}
